﻿using System;
using System.Collections;
using System.Text.RegularExpressions;
using System.Windows;
using AutoKoC.Models;
using CSharp.Libs.Koc;
using CSharp.Libs.WPF;
using System.Windows.Input;


namespace AutoKoC.ViewModels
{
    class AutoKoCViewModel : ViewModelBase
    {
        #region declarations
        private AppBase _AB = null;

        private RelayCommand _rcReloadServer = null;

        private String _strNavigateUrl = "";
        private String _strReloadKocUrl = "";
        #endregion



        #region constructor / terminator
        public AutoKoCViewModel(
            AppBase AB)
        {
            _AB = AB;
            _strNavigateUrl = _AB.LAO.GetOption(constants.LAO_FACEBOOK_URL);
            _strReloadKocUrl = _AB.LAO.GetOption(constants.LAO_KOC_RELOAD_URL);
            _readCustomServers();

            _AB.TM.SeedChanged += new TrafficMonitor.SeedChangedEventHandler(TM_SeedChanged);
            _AB.TM.FbParametersChanged += new TrafficMonitor.FbParametersChangedEventHandler(TM_FbParametersChanged);
            _AB.TM.UserIsValidChanged += new TrafficMonitor.UserIsValidChangedEventHandler(TM_UserIsValidChanged);
            _AB.TM.KocServerChanged += new TrafficMonitor.KocServerChangedEventHandler(TM_KocServerChanged);

            _AB.AKR.ReloadServerIdChanged += new AutoKocReloader.ReloadServerIdChangedEventHandler(AKR_ReloadServerIdChanged);

            _AB.LAO.OptionsChanged += new CSharp.Libs.Misc.LocalApplicationOptions.OptionsChangedEventHandler(LAO_OptionsChanged);
        }

        ~AutoKoCViewModel()
        {
            _rcReloadServer = null;

            if (_AB != null)
            {
                if (_AB.LAO != null)
                {
                    _AB.LAO.OptionsChanged -= LAO_OptionsChanged;
                }
                if (_AB.AKR != null)
                {
                    _AB.AKR.ReloadServerIdChanged -= AKR_ReloadServerIdChanged;
                }
                if (_AB.TM != null)
                {
                    _AB.TM.UserIsValidChanged -= TM_UserIsValidChanged;
                    _AB.TM.FbParametersChanged -= TM_FbParametersChanged;
                    _AB.TM.SeedChanged -= TM_SeedChanged;
                    _AB.TM.KocServerChanged -= TM_KocServerChanged;
                }

                _AB = null;
            }
        }
        #endregion



        #region event handling
        void TM_SeedChanged(object sender)
        {
            OnPropertyChanged("SeedCount");
            OnPropertyChanged("NotAuthorizedText");
        }

        void TM_FbParametersChanged(object sender)
        {
            OnPropertyChanged("FbParametersExist");
        }

        void TM_UserIsValidChanged(object sender)
        {
            OnPropertyChanged("UserIsValid");
            OnPropertyChanged("NotAuthorizedText");
        }

        void TM_KocServerChanged(object sender)
        {
            OnPropertyChanged("ReloadServerId");
        }

        void AKR_ReloadServerIdChanged(object sender)
        {
            OnPropertyChanged("ReloadServerId");
        }

        void LAO_OptionsChanged(object sender)
        {
            _readCustomServers();
        }
        #endregion



        #region private functions
        //private void _GetMyServers()
        //{
        //    try
        //    {
        //        if (!_AB.UH.URLMyServers.URLMaybeValid)
        //        {
        //            //Generate Command (without own parameters -> myServers.php) out of getChat.php
        //            _AB.UH.ParseURLMyServers(_AB.UH.URLGetChat.GetURL().Replace(URLHolder.PHP_GET_CHAT, URLHolder.PHP_MY_SERVERS));

        //            //Remove GetChat specific parameters
        //            _AB.UH.URLMyServers.Parameters.Remove(URLHolder.PARAM_CTYPE);
        //            _AB.UH.URLMyServers.Parameters.Remove(URLHolder.PARAM_CTYPE_ID);
        //            _AB.UH.URLMyServers.Parameters.Remove(URLHolder.PARAM_CUR_NEWEST_1);
        //            _AB.UH.URLMyServers.Parameters.Remove(URLHolder.PARAM_CUR_NEWEST_2);
        //            _AB.UH.URLMyServers.Parameters.Remove(URLHolder.PARAM_CUR_NEWEST_3);
        //            _AB.UH.URLMyServers.Parameters.Remove(URLHolder.PARAM_SID);
        //        }

        //        if (_AB.UH.URLMyServers.URLMaybeValid)
        //        {
        //            Hashtable htResult = null;
        //            if (_AB.UH.URLMyServers.GetAnswerHashtable(out htResult))
        //            {
        //                String Data = htResult[constants.KEY_DATA].ToString();
        //                //Int32 intStartIndex = 0;
        //                //Int32 intEndIndex = 0;
                        
        //            }
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        _AB.EC.AddException(ex, this.ToString(), _AB.EC.Tools.GetCurrentMethodName());
        //    }
        //}

        /// <summary>_readCustomServers
        /// 
        /// </summary>
        /// <history>29.04.2011</history>
        private void _readCustomServers()
        {
            try
            {
                String strCustomServer = _AB.LAO.GetOption(constants.LAO_KOC_CUSTOM_SERVER_1);
                if (strCustomServer == "")
                {
                    _AB.LAO.SetOption(constants.LAO_KOC_CUSTOM_SERVER_1, "0");
                }
                Int32.TryParse(_AB.LAO.GetOption(constants.LAO_KOC_CUSTOM_SERVER_1), out _intCustomServer1);
                
                strCustomServer = _AB.LAO.GetOption(constants.LAO_KOC_CUSTOM_SERVER_2);
                if (strCustomServer == "")
                {
                    _AB.LAO.SetOption(constants.LAO_KOC_CUSTOM_SERVER_2, "0");
                }
                Int32.TryParse(_AB.LAO.GetOption(constants.LAO_KOC_CUSTOM_SERVER_2), out _intCustomServer2);

                strCustomServer = _AB.LAO.GetOption(constants.LAO_KOC_CUSTOM_SERVER_3);
                if (strCustomServer == "")
                {
                    _AB.LAO.SetOption(constants.LAO_KOC_CUSTOM_SERVER_3, "0");
                }
                Int32.TryParse(_AB.LAO.GetOption(constants.LAO_KOC_CUSTOM_SERVER_3), out _intCustomServer3);

                strCustomServer = _AB.LAO.GetOption(constants.LAO_KOC_CUSTOM_SERVER_4);
                if (strCustomServer == "")
                {
                    _AB.LAO.SetOption(constants.LAO_KOC_CUSTOM_SERVER_4, "0");
                }
                Int32.TryParse(_AB.LAO.GetOption(constants.LAO_KOC_CUSTOM_SERVER_4), out _intCustomServer4);

                strCustomServer = _AB.LAO.GetOption(constants.LAO_KOC_CUSTOM_SERVER_5);
                if (strCustomServer == "")
                {
                    _AB.LAO.SetOption(constants.LAO_KOC_CUSTOM_SERVER_5, "0");
                }
                Int32.TryParse(_AB.LAO.GetOption(constants.LAO_KOC_CUSTOM_SERVER_5), out _intCustomServer5);

                OnPropertyChanged("CustomServer1");
                OnPropertyChanged("CustomServer2");
                OnPropertyChanged("CustomServer3");
                OnPropertyChanged("CustomServer4");
                OnPropertyChanged("CustomServer5");
            }
            catch (Exception ex)
            {
                _AB.EC.AddException(ex, this.ToString(), _AB.EC.Tools.GetCurrentMethodName());
            }
        }

        /// <summary>_ReloadServer
        /// 
        /// </summary>
        /// <history>29.04.2011</history>
        private void _ReloadServer(
            Int32 ReloadServerID)
        {
            try
            {
                if (ReloadServerID > 0)
                {
                    _AB.AKR.ReloadServerId = ReloadServerID;
                    _AB.AKR.Reload(_AB.AKR.ReloadServerId);
                }
            }
            catch (Exception ex)
            {
                _AB.EC.AddException(ex, this.ToString(), _AB.EC.Tools.GetCurrentMethodName());
            }
        }

        private void _ReloadServer()
        {
            try
            {
                _AB.AKR.Reload(_AB.AKR.ReloadServerId);
            }
            catch (Exception ex)
            {
                _AB.EC.AddException(ex, this.ToString(), _AB.EC.Tools.GetCurrentMethodName());
            }
        }
        #endregion



        #region interface
        #region properties
        public String NavigateURL
        {
            get
            {
                return _strNavigateUrl;
            }
        }

        public Boolean NavigateUrlIsValid
        {
            get
            {
                return isValidUrl(_strNavigateUrl);
            }
        }

        public String ReloadKocUrl
        {
            get
            {
                return _strReloadKocUrl;
            }
        }

        public Boolean ReloadKocUrlIsValid
        {
            get
            {
                return isValidUrl(_strReloadKocUrl);
            }
        }

        public Int32 SeedCount
        {
            get
            {
                return _AB.TM.SeedCount;
            }
        }

        public Boolean FbParametersExist
        {
            get
            {
                return _AB.UH.URLGetChat.URLMaybeValid && _AB.TM.UserIsValid;
            }
        }

        public Visibility UserIsValid
        {
            get
            {
                if (_AB.TM.UserIsValid)
                {
                    return Visibility.Visible;
                }
                else
                {
                    return Visibility.Hidden;
                }
            }
        }

        public String NotAuthorizedText
        {
            get
            {
                if(!_AB.TM.UserIsValid && _AB.TM.FBUserID != "")
                {
                    return "You are not authorized to use this software !";
                }
                else
                {
                    return "";
                }
            }
        }

        #region manual reload server
        public Int32 ReloadServerId
        {
            get
            {
                return _AB.AKR.ReloadServerId;
            }
            set
            {
                _AB.AKR.ReloadServerId = value;
            }
        }

        public ICommand ReloadServer
        {
            get
            {
                if (_rcReloadServer == null)
                {
                    _rcReloadServer = new RelayCommand(
                        param => this._ReloadServer(),
                        param => this.CanReloadServer);
                }
                return _rcReloadServer;
            }
        }
        public Boolean CanReloadServer
        {
            get
            {
                return true;
            }
        }
        #endregion

        #region custom servers
        private const String CUSTOM_SERVER_INACTIVE = "none";
        
        private Int32 _intCustomServer1 = -1;
        private Int32 _intCustomServer2 = -1;
        private Int32 _intCustomServer3 = -1;
        private Int32 _intCustomServer4 = -1;
        private Int32 _intCustomServer5 = -1;

        private RelayCommand _rcReloadCustomServer1 = null;
        private RelayCommand _rcReloadCustomServer2 = null;
        private RelayCommand _rcReloadCustomServer3 = null;
        private RelayCommand _rcReloadCustomServer4 = null;
        private RelayCommand _rcReloadCustomServer5 = null;

        public String CustomServer1
        {
            get
            {
                if (_intCustomServer1 > 0)
                {
                    return _intCustomServer1.ToString();
                }
                else
                {
                    return CUSTOM_SERVER_INACTIVE;
                }
            }
        }

        public String CustomServer2
        {
            get
            {
                if (_intCustomServer2 > 0)
                {
                    return _intCustomServer2.ToString();
                }
                else
                {
                    return CUSTOM_SERVER_INACTIVE;
                }
            }
        }

        public String CustomServer3
        {
            get
            {
                if (_intCustomServer3 > 0)
                {
                    return _intCustomServer3.ToString();
                }
                else
                {
                    return CUSTOM_SERVER_INACTIVE;
                }
            }
        }

        public String CustomServer4
        {
            get
            {
                if (_intCustomServer4 > 0)
                {
                    return _intCustomServer4.ToString();
                }
                else
                {
                    return CUSTOM_SERVER_INACTIVE;
                }
            }
        }

        public String CustomServer5
        {
            get
            {
                if (_intCustomServer5 > 0)
                {
                    return _intCustomServer5.ToString();
                }
                else
                {
                    return CUSTOM_SERVER_INACTIVE;
                }
            }
        }

        public ICommand ReloadCustomServer1
        {
            get
            {
                if (_rcReloadCustomServer1 == null)
                {
                    _rcReloadCustomServer1 = new RelayCommand(
                        param => this._ReloadServer(_intCustomServer1),
                        param => this.CanReloadCustomServer1);
                }
                return _rcReloadCustomServer1;
            }
        }
        public Boolean CanReloadCustomServer1
        {
            get
            {
                return _intCustomServer1 > 0;
            }
        }

        public ICommand ReloadCustomServer2
        {
            get
            {
                if (_rcReloadCustomServer2 == null)
                {
                    _rcReloadCustomServer2 = new RelayCommand(
                        param => this._ReloadServer(_intCustomServer2),
                        param => this.CanReloadCustomServer2);
                }
                return _rcReloadCustomServer2;
            }
        }
        public Boolean CanReloadCustomServer2
        {
            get
            {
                return _intCustomServer2 > 0;
            }
        }

        public ICommand ReloadCustomServer3
        {
            get
            {
                if (_rcReloadCustomServer3 == null)
                {
                    _rcReloadCustomServer3 = new RelayCommand(
                        param => this._ReloadServer(_intCustomServer3),
                        param => this.CanReloadCustomServer3);
                }
                return _rcReloadCustomServer3;
            }
        }
        public Boolean CanReloadCustomServer3
        {
            get
            {
                return _intCustomServer3 > 0;
            }
        }

        public ICommand ReloadCustomServer4
        {
            get
            {
                if (_rcReloadCustomServer4 == null)
                {
                    _rcReloadCustomServer4 = new RelayCommand(
                        param => this._ReloadServer(_intCustomServer4),
                        param => this.CanReloadCustomServer4);
                }
                return _rcReloadCustomServer4;
            }
        }
        public Boolean CanReloadCustomServer4
        {
            get
            {
                return _intCustomServer4 > 0;
            }
        }

        public ICommand ReloadCustomServer5
        {
            get
            {
                if (_rcReloadCustomServer5 == null)
                {
                    _rcReloadCustomServer5 = new RelayCommand(
                        param => this._ReloadServer(_intCustomServer5),
                        param => this.CanReloadCustomServer5);
                }
                return _rcReloadCustomServer5;
            }
        }
        public Boolean CanReloadCustomServer5
        {
            get
            {
                return _intCustomServer5 > 0;
            }
        }
        #endregion
        #endregion

        #region methods
        /// <summary>isValidUrl
        /// method for validating a url with regular expressions
        /// </summary>
        /// <param name="url">url we're validating</param>
        /// <returns>true if valid, otherwise false</returns>
        public static Boolean isValidUrl(String url)
        {
            string pattern = @"^(http|https|ftp)\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&amp;%\$#\=~])*[^\.\,\)\(\s]$";
            Regex reg = new Regex(pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
            return reg.IsMatch(url);
        }
        #endregion
        #endregion
    }
}
